using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Alarms.Queries;

/// <summary>
/// 设备警报记录分页查询命令。
/// </summary>
public sealed record class GetAlarmRecordListWithPagedQuery(
    string? LineCode,
    string? WorkCenter,
    string? Classify,
    DateTime? StartTime,
    DateTime? EndTime,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<EquipAlarmRecordDto>>>;

internal sealed class GetAlarmRecordListWithPagedQueryHandler(IRepository<EquipAlarmRecord> repo) : IRequestHandler<GetAlarmRecordListWithPagedQuery, IResult<PagedList<EquipAlarmRecordDto>>>
{
    public async Task<IResult<PagedList<EquipAlarmRecordDto>>> Handle(GetAlarmRecordListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(request.LineCode), m => m.LineCode == request.LineCode)
            .WhereIF(!string.IsNullOrEmpty(request.WorkCenter), m => m.WorkCenter == request.WorkCenter)
            .WhereIF(!string.IsNullOrEmpty(request.Classify), m => m.Classify == request.Classify)
            .WhereIF(request.StartTime != null, m => m.StartTime >= request.StartTime.MinTime())
            .WhereIF(request.EndTime != null, m => m.StartTime <= request.EndTime.MaxTime())
            .OrderByDescending(m => m.StartTime)
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);

        return Result.From(items.Adapt<PagedList<EquipAlarmRecordDto>>());
    }
}
